#include "pch.h"
#include "GRiMeshLoader.h"
#include <GGenericInfra/GGiEngineUtil.h>

using namespace std;


GRiMeshLoader& GRiMeshLoader::Get()
{
	// TODO: 在此处插入 return 语句
	static GRiMeshLoader* instance = new GRiMeshLoader();
	return *instance;
}

void GRiMeshLoader::ImportMesh(std::string FileName, std::vector<GRiMeshData>& outMeshDataList)
{
	Assimp::Importer import;
	const aiScene* scene = import.ReadFile(FileName, 
		aiProcess_Triangulate |
		aiProcess_FlipUVs | 
		aiProcess_GenNormals | 
		aiProcess_CalcTangentSpace);

	if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
	{
		string errorInfo ="ERROR::ASSIMP::";
		errorInfo += import.GetErrorString();

		MessageBox(NULL, GGiEngineUtil::StringToWString(errorInfo).c_str(), L"", MB_OK);
		throw(errorInfo);
		
		return;
	}

	ProcessNode(scene->mRootNode, scene, outMeshDataList);

	return ;
}

void GRiMeshLoader::ProcessNode(aiNode* node, const aiScene* scene,std::vector<GRiMeshData>& outMeshDataList)
{
	// 处理节点所有的网格（如果有的话）
	for (unsigned int i = 0; i < node->mNumMeshes; i++)
	{
		aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
		ProcessMesh(mesh, scene, outMeshDataList);
	}
	// 接下来对它的子节点重复这一过程
	for (unsigned int i = 0; i < node->mNumChildren; i++)
	{
		ProcessNode(node->mChildren[i], scene, outMeshDataList);
	}
}

void GRiMeshLoader::ProcessMesh(aiMesh* mesh, const aiScene* scene, std::vector<GRiMeshData>& outMeshDataList)
{
	vector<GRiVertex> vertices;
	vector<uint32_t> indices;
	vector<uint32_t> textures;

	for (unsigned int i = 0; i < mesh->mNumVertices; i++)
	{
		GRiVertex vertex = {};
		vertex.Position[0] = mesh->mVertices[i].x;
		vertex.Position[1] = mesh->mVertices[i].y;
		vertex.Position[2] = mesh->mVertices[i].z;

		vertex.Normal[0] = mesh->mNormals[i].x;
		vertex.Normal[1] = mesh->mNormals[i].y;
		vertex.Normal[2] = mesh->mNormals[i].z;

		//if (mesh->mTangents[0]) // 网格是否有纹理坐标？
		{
			vertex.TangentU[0] = mesh->mTangents[i].x;
			vertex.TangentU[1] = mesh->mTangents[i].y;
			vertex.TangentU[2] = mesh->mTangents[i].z;
		}
		
		if (mesh->mTextureCoords[0]) // 网格是否有纹理坐标？
		{
			vertex.UV[0] = mesh->mTextureCoords[0][i].x;
			vertex.UV[1] = mesh->mTextureCoords[0][i].y;
		}
		vertices.push_back(vertex);
	}

	for (unsigned int i = 0; i < mesh->mNumFaces; i++)
	{
		aiFace face = mesh->mFaces[i];
		for (unsigned int j = 0; j < face.mNumIndices; j++)
			indices.push_back(face.mIndices[j]);
	}

	outMeshDataList.push_back(GRiMeshData(to_string(outMeshDataList.size()), vertices, indices));
}
